﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Controls;
using VAdvantage.Classes;
using System.Windows;
using System.Windows.Data;
namespace VAdvantage.Controls
{
    public class VAmountTextBox : CTextBox, IControl, ITextChangedEvent
    {
        #region Variables

        // char key message
        private const int WM_CHAR = 0x0102;
        // mouse message in ContextMenu on right Click
        //private const int WM_CUT = 0x0300;
        //// mouse message in ContextMenu
        //private const int WM_COPY = 0x0301; 
        //// mouse message in ContextMenu
        //private const int WM_PASTE = 0x0302;
        //// mouse message in ContextMenu
        //private const int WM_CLEAR = 0x0303;
        ////To include -ve sign in text box
        private char _negativeSign = '-';
        //text limit
        private const int _MAXLENGTH = 50;
        //allow decimal key
        private bool _allowNegative = true;
        //check decimal variable
        private char _decimalSeparator = '.';
        //Variable to handle Space in textbox
        Boolean allowSpace = false;
        private bool isChanged = true;
        private bool isSelected = false;
        private Format _format = null;

        private bool _focus;
        private Binding binding;


        #endregion

        #region Property

        public static readonly DependencyProperty TextValueProperty =
         DependencyProperty.Register("TextValue", typeof(Decimal?), typeof(VAdvantage.Controls.VAmountTextBox), new PropertyMetadata((o, e) =>
         {
             ((VAmountTextBox)o).SetTextValue((Decimal?)e.NewValue);

         }));


        public Decimal? TextValue
        {
            get
            {
                return ((int?)GetValue(VAmountTextBox.TextValueProperty));
            }
            set
            {
                SetValue(VAmountTextBox.TextValueProperty, value);
            }
        }

        void SetTextValue(Decimal? newVal)
        {
            //TextValue = newVal;

            if (newVal == null)
            {
                this.Text = "";
            }
            else
            {
                this.Text = String.Format(_format.GetFormat(), Decimal.Parse(newVal.ToString())); //_format.GetFormatedValue(Decimal.Parse(TextValue.ToString()));
            }
            SetColor();
            //SetGetValue(id, false);
        }


        #endregion


        #region Constructor
        /// <summary>
        /// Default Class Constructor
        /// </summary>
        public VAmountTextBox()
            : base()
        {
            this.TextChanged += new System.Windows.Controls.TextChangedEventHandler(VAmountTextBox_TextChanged);

            _displayType = DisplayType.Number;
            _format = DisplayType.GetNumberFormat(DisplayType.Number);

        }

        void VAmountTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {

            // base.OnTextChanged(e);
            if (_textSetting)
                return;
            SetColor();
            //commented for SL
            //if (EditingControlDataGridView != null)
            //{
            //    EditingControlValueChanged = true;
            //    EditingControlDataGridView.NotifyCurrentCellDirty(true);
            //    //EditingControlDataGridView.CurrentCell.Value = this.GetValue();
            //}

            //if (isChanged)
            //{
            //    if (FireTextChanged != null)
            //    {
            //        FireTextChanged(this, e);
            //    }
            //}
        }

        public VAmountTextBox(int displayType)
        {
            _displayType = displayType;
            _format = DisplayType.GetNumberFormat(_displayType);
            //Control Design
            //InitializeComponent();
            //this.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
        }

        /// <summary>
        /// Parametrised Constructor
        /// </summary>
        /// <param name="columnName">Displayed column name</param>
        /// <param name="mandatory">Bool Type(mendatory status)</param>
        /// <param name="isReadOnly">Bool Type(readonly status)</param>
        /// <param name="isUpdateable">Bool type(is update able)</param>
        /// <param name="displayType">display Integer value</param>
        /// <param name="title">set title</param>
        public VAmountTextBox(String columnName, bool mandatory, bool isReadOnly, bool isUpdateable,
                        int displayType, String title)
            : base()
        {
            //Control Design
            //InitializeComponent();

            

            base.TextAlignment = TextAlignment.Right;
            _columnName = columnName;
            _title = title;
            _displayType = displayType;
            _mandatory = mandatory;
            if (isReadOnly || !isUpdateable)
            {
                SetReadOnly(true);
                //this.Enabled = false;
                //this.ContextMenu = new ContextMenu();
            }
            else
            {
                SetReadOnly(false);
            }


            _format = DisplayType.GetNumberFormat(displayType);
            this.MaxLength = 40;

            this.TextChanged += VAmountTextBox_TextChanged;
            //Commented for SL
            //this.DataBindings.DefaultDataSourceUpdateMode = DataSourceUpdateMode.Never;
            CheckCulture();
        }

       


        private bool IsTextChanged()
        {
            string value = "";
            string value2 = "";
            if (_field.GetValue() != null)
            {
                value = _field.GetValue().ToString().Replace(",", "");
                if (value.IndexOf('.') < 0)
                {
                    value += ".00";
                }
            }
                value2 = this.Text.Replace(",", "");
                if (value2.IndexOf('.') < 0)
                {
                    value2 += ".00";
                }
            
            return value != value2;
        }

        /// <summary>
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            // this.SuspendLayout();
            // 
            // VAmountTextBox
            // 

            // this.ResumeLayout(false);

        }

        #endregion

        //static System.Globalization.NumberFormatInfo ni = null;
        static char decimalSeperator = '.';
        static VAmountTextBox()
        {
            System.Globalization.CultureInfo ci =
             System.Globalization.CultureInfo.CurrentUICulture;
            char.TryParse(ci.NumberFormat.NumberDecimalSeparator, out decimalSeperator);

            //ni = (System.Globalization.NumberFormatInfo)
            //  ci.NumberFormat.Clone();
        }

        private void CheckCulture()
        {
            char sep = decimalSeperator;
            System.Globalization.CultureInfo ci =
             System.Globalization.CultureInfo.CurrentUICulture;
            char.TryParse(ci.NumberFormat.NumberDecimalSeparator, out sep);
            if (decimalSeperator != sep)
            {
                decimalSeperator = sep;
            }
        }


        #region Properties
        /// <summary>
        /// IntValue is Read Only property of textbox control
        /// take only integer value
        /// </summary>
        public int IntValue
        {
            get
            {
                return Int32.Parse(this.Text);
            }
        }
        /// <summary>
        /// DecimalValue is Read Only property of textbox control
        /// take only Decimal value
        /// </summary>
        public decimal DecimalValue
        {
            get
            {
                return Decimal.Parse(this.Text);
            }
        }
        /// <summary>
        /// AllowSpace is property to set Space in textbox 
        /// take only Decimal value
        /// </summary>
        public bool AllowSpace
        {
            set
            { this.allowSpace = value; }
            get
            { return this.allowSpace; }
        }

        #endregion

        public event EventHandler VetoableChangeListener;
        public event EventHandler FireTextChanged;
        #region override Events

        #region OnKeyPress Event
        /// <summary>
        /// OnKeyPress Event Handles the BackSpace Key function,
        /// Decimal and other key press also Check on Value entered 
        /// on textbox
        /// </summary>
        /// <param name="e">current key agument</param>

        private char _inputChar = ' ';

        protected override void OnKeyDown(KeyEventArgs e)
        {
            Key inputKey = e.Key;
            if (e.PlatformKeyCode == 189)
                inputKey = Key.Subtract;
            if (e.PlatformKeyCode == 190||e.PlatformKeyCode==110)
                _inputChar = '.';
            /* Check Only for . and , */
            if (e.PlatformKeyCode == 188)
                _inputChar = ',';


            isChanged = false; //so that unrequired function will not call on change event

            //Call Checkdecimal function For decimal entery

            e.Handled = CheckDecimal(inputKey);
            _inputChar = ' ';
            //Back space Check
            if (inputKey == Key.Back)
            {
                //false the current Handler
                e.Handled = false;
            }
            //Call Check function after Setting Decimal value
            check();

            try
            {
                //allow -ve sign
                if (!_allowNegative && inputKey == Key.Subtract && base.Text.IndexOf(_negativeSign) < 0)
                {
                    //enable the handler
                    e.Handled = true;
                    //return the value
                    return;
                }

                //check the condition on -ve value
                bool isNegative = false;
                if (base.Text.Length > 0)
                {
                    isNegative = (base.Text[0] == _negativeSign) ? true : false;
                }

                //place -ve sign and the starting potion
                if (isNegative && this.SelectionStart == 0)
                {
                    //set the position for -ve sign
                    this.SelectionStart = 1;
                }
                //if pressed -ve
                if (inputKey == Key.Subtract)
                {
                    //store the -ve 
                    int selStart = this.SelectionStart;
                    //not -ve sign this is [logic to covert -ve to positive]
                    if (!isNegative)
                    {
                        //plce -ve with text
                        base.Text = _negativeSign + base.Text;
                        //set the cursor postion
                        this.SelectionStart = selStart + 1;
                    }
                    else
                    {
                        //to remove -ve sign set the length for text and cursor
                        base.Text = base.Text.Substring(1, base.Text.Length - 1);
                        //if selected text is greater then one
                        if (selStart >= 1)
                        {
                            //set Cursor
                            this.SelectionStart = selStart - 1;
                        }
                        else
                        {
                            //other set to 0
                            this.SelectionStart = 0;
                        }
                    }
                    // minus(-) has been handled
                    e.Handled = true;
                    //return value
                    return;
                }
                ////if text box contains default text in textbox
                if (base.Text == "0.00")
                {
                    //set the cursor postion
                    this.SelectionStart = 0;
                    // replace thre first char, ie. 0
                    this.SelectionLength = 1;
                }
                //check (-0) value in text box
                else if (base.Text == _negativeSign + "0")
                {
                    //set thepostion
                    this.SelectionStart = 1;
                    // replace thre first char, ie. 0
                    this.SelectionLength = 1;
                }
                isChanged = true;
                base.OnKeyDown(e);
            }
            catch (Exception ex)
            {
                //return nothing on _Error_Large value
                return;
            }
        }

        #endregion







        #region OnLeave Event
        /// <summary>
        /// Event fiers when textbox lost focus
        /// set the textbox value According to the calture
        /// also check entered text formate
        /// </summary>
        /// <param name="e">current argument</param>

        protected override void OnLostFocus(RoutedEventArgs e)
        {

            try
            {
                isChanged = false;
                //if text box is empty
                if (string.IsNullOrEmpty(this.Text))//if(this.text=="")
                {
                    //if no text set default text
                    this.Text = "";//String.Format(_format.GetFormat(), 0);

                }
                else
                {
                    //if contains the decimal in the text
                    if (this.Text.Contains(decimalSeperator.ToString()))// "."))
                    {
                        //RoundUp the text box text to decimal place
                        this.Text = decimal.Round(Convert.ToDecimal(this.Text), _format.MaxFractionDigit).ToString();
                    }
                    //if text doesn't have .00 value
                    else if (!this.Text.Contains(".00"))
                    {
                        //Append zero to last of text
                        //base.Text = this.Text + ".00";
                    }
                }


                //this.Text = String.Format("{0:0.00}", Decimal.Parse(this.Text.ToString()));
                if (this.Text != "")
                {
                    this.Text = String.Format(_format.GetFormat(), Decimal.Parse(this.Text.ToString()));
                }
                //Commented for SL
                //if (EditingControlDataGridView == null && IsTextChanged())
                if (IsTextChanged())
                {
                    if (VetoableChangeListener != null)
                    {
                        VetoableChangeListener(this, e);
                    }
                }


                isChanged = true;
                isSelected = false;
                if (IsReadOnly)
                {
                    SetBackGround(true);
                }
            }
            catch (Exception ex)
            {
                return;//return nothing
            }
            //base method

            _focus = false;
            base.OnLostFocus(e);
        }
        #endregion

        #endregion

        #region Private Methods

        #region CheckDecimal
        /// <summary>
        /// function check the decimal charector
        /// set the Current cursor positon
        /// using SelectionStart
        /// </summary>
        /// <param name="chr">To enter the decimal charactor</param>
        /// <returns>Bool type(true if get the decimal)</returns>
        private bool CheckDecimal(char chr)
        {
            try
            {
                //if pressed charector
                if (Char.IsDigit(chr))
                {
                    //no return
                    return false;
                }
                //check for the dot
                else if (chr == decimalSeperator)//  '.')
                {
                    //set current cursor postion
                    int ipos = this.SelectionStart;
                    //text contains dot in the textbox
                    if (this.Text.Contains(decimalSeperator.ToString()))//   "."))
                    {
                        //replace the dot text
                        this.Text = this.Text.Replace(decimalSeperator.ToString(), "");//   ".", "");
                        //set the dot postion after dot replacement
                        this.Text = this.Text.Insert(ipos - 1, decimalSeperator.ToString());// ".");
                    }
                    else
                    {
                        //insert the cursor postion after the dot postion
                        this.Text = this.Text.Insert(ipos, decimalSeperator.ToString());// ".");
                    }
                    //set starting postion of the textbox in textbox according to length
                    this.SelectionStart = this.Text.Length;
                    //return the value
                    return true;
                    ;
                }
                else
                {
                    //return value to textbox
                    return true;
                }
            }
            catch (Exception ex)
            {
                //if exception no return
                return false;
            }
        }
        private bool CheckDecimal(Key chr)
        {
            try
            {
                //if pressed charector
                if (CheckInputKeyIsDigit(chr))
                {
                    //no return
                    return false;
                }
                //check for the dot
                else if (_inputChar.Equals(decimalSeperator))//  '.')
                {
                    //set current cursor postion
                    int ipos = this.SelectionStart;
                    //text contains dot in the textbox
                    if (this.Text.Contains(decimalSeperator.ToString()))//   "."))
                    {
                        //replace the dot text
                        this.Text = this.Text.Replace(decimalSeperator.ToString(), "");//   ".", "");
                        //set the dot postion after dot replacement
                        this.Text = this.Text.Insert(ipos - 1, decimalSeperator.ToString());// ".");
                    }
                    else
                    {
                        //insert the cursor postion after the dot postion
                        this.Text = this.Text.Insert(ipos, decimalSeperator.ToString());// ".");
                    }
                    //set starting postion of the textbox in textbox according to length
                    this.SelectionStart = this.Text.Length;
                    //return the value
                    return true;
                    ;
                }
                else
                {
                    //return value to textbox
                    return true;
                }
            }
            catch (Exception ex)
            {
                //if exception no return
                return false;
            }
        }

        private bool CheckInputKeyIsDigit(Key k)
        {

            bool retVal = false;
            //check for digit
            if ((k >= Key.D0 && k <= Key.D9) || (k >= Key.NumPad0 && k <= Key.NumPad9))
            {
                retVal = true;
            }


            //check for backspace, tab, up, down, left, right keys
            //if ((k == Key.Back) || (k == Key.Tab) || (k == Key.Left || k == Key.Right || k == Key.Up || k == Key.Down))
           if ((k == Key.Back) || (k == Key.Tab) || (k == Key.Left || k == Key.Right || k == Key.Up || k == Key.Down||k==Key.Delete))
            {
                retVal = true;
            }
            return retVal;
        }

        #endregion

        #region check()
        /// <summary>
        /// function Place Zero At
        /// Begning of decimal when no text there
        /// </summary>
        private void check()
        {
            //set initialize count for the entered text
            int count = 0;
            //get length of text
            count = Convert.ToInt32(this.Text.Length);
            /*if (this.Text == "00")
            {
                this.Text = "";
            }
            else*/
            //if text contains"0.00"
            if (this.Text == "0.00")
            {
                //empty the text  
                this.Text = "";
            }
            //check the condition for decimal value when only one decimal in the tetxbox
            else if (count == 1 && this.Text == decimalSeperator.ToString())//  ".")
            {
                //then add zero before the text box for the amount
                this.Text = 0 + this.Text;
                //select the start postion of the cursor according to the length of the text 
                this.SelectionStart = this.Text.Length;
            }


        }
        #endregion

        #region ClearSelection Method
        /// <summary>
        /// ClearSelection: function used to clear the textbox
        /// On commad i.e.Cut,Copy,Past
        /// </summary>
        //private void ClearSelection()
        //{
        //    //if selected length is 0
        //    if (this.SelectionLength == 0)
        //    {
        //        //no value will return
        //        return;
        //    }
        //    //if selected length and textbox length equal
        //    if (this.SelectedText.Length == base.Text.Length)
        //    {
        //        //place 0 in the textbox
        //        base.Text = 0.ToString();
        //        //return value
        //        return;
        //    }
        //    //put the lengthin variable
        //    int selLength = this.SelectedText.Length;
        //    // after selected text
        //    this.SelectionStart += this.SelectedText.Length;
        //    // after selected text
        //    this.SelectionLength = 0;
        //    //for selected text slection
        //    for (int k = 1; k <= selLength; k++)
        //    {
        //        //this.DeleteText(Keys.Back);
        //    }
        //}
        #endregion

        #region SendCharKey()
        /// <summary>
        /// handel the string message
        /// on Cut,Copyand Past in text box
        /// </summary>
        /// <param name="charKey">key press argument</param>
        //private void SendCharKey(char c)
        //{
        //    //create instance of message
        //    Message msg = new Message();
        //    //use handle
        //    msg.HWnd = this.Handle;
        //    //message contains Charector String
        //    msg.Msg = WM_CHAR;
        //    //set the pointer
        //    msg.WParam = (IntPtr)c;
        //    //only put zero in textbox
        //    msg.LParam = IntPtr.Zero;
        //    //base method
        //    base.WndProc(ref msg);
        //}
        #endregion

        #endregion

        /***********************************************************/

        #region "Declaration"
        //set control name as column name 
        private String _columnName;
        protected int _displayType;	//  Currency / UoM via Context
        //private DecimalFormat m_format;
        private String _title;
        //setting string
        private bool _setting;
        //old text
        private String _oldText;
        private String _initialText;
        private bool _rangeSet = false;
        //max and min text length
        private Double _minValue;
        private Double _maxValue;
        //modifire status
        private bool _modified = false;
        private Grids.GridField _field = null;
        //mendetory status
        private bool _mandatory;
        //read only status
        private bool _readOnly;
        #endregion

        #region Icontrol

        /// <summary>
        /// mendatory text box
        /// </summary>
        /// <returns>Bool type (interface)</returns>
        public bool GetIsMandatory()
        {
            return _mandatory;
        }
        /// <summary>
        /// Sets Mandatory
        /// </summary>
        /// <param name="value">bool type value</param>
        public void SetIsMandatory(bool value)
        {
            _mandatory = value;
        }
        /// <summary>
        /// readonly text box
        /// </summary>
        /// <returns>Bool type(read only status)</returns>
        public bool GetIsReadonly()
        {
            return _readOnly;
        }
        /// <summary>
        /// field class Object to get field
        /// </summary>
        /// <returns>class fields</returns>
        public Grids.GridField GetField()
        {
            return _field;
        }
        public string GetSelectedText()
        {
            return this.SelectedText;

        }
        /// <summary>
        /// set field from field class
        /// </summary>
        /// <param name="field">set field of Model.GridField class</param>
        public void SetField(Grids.GridField field)
        {
            _field = field;
        }
        /// <summary>
        /// display type
        /// </summary>
        /// <returns>Disply value</returns>
        public int GetDisplayType()
        {
            return _displayType;
        }
        /// <summary>
        /// set the control display type
        /// </summary>
        /// <param name="displayType">get the display type</param>
        public void SetDisplayType(int displayType)
        {
            _displayType = displayType;
        }
        /// <summary>
        /// get contriol name
        /// </summary>
        /// <returns>set disply value</returns>
        public string GetName()
        {
            return this._columnName;
        }
        /// <summary>
        /// value of control
        /// </summary>
        /// <returns>control value</returns>
        /// Harwinder
        /// *** dont write 
        public object GetValue()
        {
            if (this.Text.Trim() == "" || this.Text.Trim() == "-")
            {
                //if (_field != null)
                //    return null;
                //else
                //{
                return null;
                // }
            }

            try { return Decimal.Parse(this.Text.Trim()); }
            catch
            {
                //if (_field != null)
                //{
                //    return null;
                //}
                //else
                return null;
            }
        }
        /// <summary>
        /// Set value
        /// </summary>
        /// <param name="value">value</param>
        public void SetValue(object value)
        {
            if (value == null)
                this.Text = "";
            else
                if (value == DBNull.Value)
                {
                    this.Text = String.Format(_format.GetFormat(), 0);
                }
                else if (this.Text != String.Format(_format.GetFormat(), value))
                {
                    this.Text = String.Format(_format.GetFormat(), value);
                }
        }
        private bool _textSetting = false;
        /// <summary>
        /// property bind to data
        /// </summary>
        //commented for SL
        //public object BindValue
        //{
        //    get
        //    {
        //        //return this.txtAmt.Text;
        //        return GetValue();
        //    }
        //    set
        //    {
        //        _textSetting = true;
        //        if (value == DBNull.Value)
        //        {
        //            this.Text = "";// String.Format(_format.GetFormat(), 0);
        //        }
        //        else if (this.Text != String.Format(_format.GetFormat(), value) && Text != value.ToString())
        //        {
        //            this.Text = String.Format(_format.GetFormat(), value);
        //        }
        //        SetColor();
        //        _textSetting = false;
        //    }
        //}

        private SolidColorBrush backColorBrush = new SolidColorBrush();

        public void SetReadOnly(bool readOnly)
        {
            _readOnly = readOnly;
            this.IsReadOnly = readOnly;
            this.IsTabStop = !readOnly;
            SetBackGround(readOnly);
        }

        public void SetBackGround(bool value)
        {
            if (value)
            {
                backColorBrush.Color = DataBase.GlobalVariable.READONLY_TEXT_BACK_COLOR;
                this.Background = backColorBrush;
            }
            else
            {
                backColorBrush.Color = DataBase.GlobalVariable.NORMAL_TEXT_BACK_COLOR;
                this.Background = backColorBrush;
                SetColor();
            }
        }

        private void SetColor()
        {
            if (_mandatory)
            {
                if (this.Text == "")
                {
                    backColorBrush.Color = DataBase.GlobalVariable.MANDATORY_TEXT_BACK_COLOR;
                    this.Background = backColorBrush;
                }
                else
                {
                    if (_readOnly)
                    {
                        backColorBrush.Color = DataBase.GlobalVariable.READONLY_TEXT_BACK_COLOR;
                        //this.Background = backColorBrush;
                    }
                    else
                    {


                        backColorBrush.Color = DataBase.GlobalVariable.NORMAL_TEXT_BACK_COLOR;
                    }
                    this.Background = backColorBrush;
                    if (_field != null)
                        _field.SetError(false);
                }
            }

        }


        #endregion

        /// <summary>
        /// get control text
        /// </summary>
        /// <returns>control text</returns>
        public string GetText()
        {
            return this.Text.Trim();
        }
        /// <summary>
        /// set the control text length range
        /// </summary>
        /// <param name="minValue">minimum text length</param>
        /// <param name="maxValue">maximum text length</param>
        /// <returns>bool type(for range set)</returns>
        public bool SetRange(string minValue, string maxValue)
        {
            if (minValue == null || maxValue == null || minValue == "" || minValue == "")
                return false;
            try
            {
                _minValue = Convert.ToDouble(minValue);
                _maxValue = Convert.ToDouble(maxValue);
            }
            catch (FormatException fex)
            {
                return false;
            }
            _rangeSet = true;
            return _rangeSet;
        }

        /// <summary>
        /// key up event of control compare text length
        /// </summary>
        /// <param name="sender">key</param>
        /// <param name="e">key value</param>

        protected override void OnKeyUp(KeyEventArgs e)
        {
            //base.OnKeyUp(e);
            //}
            //MessageBox.Show(_minValue.ToString() + "----" + _maxValue.ToString() + "--" + _rangeSet.ToString());
            if (e.Key == Key.Enter)
            {
                isChanged = true;
            }
            if (isChanged)
            {
                if (_rangeSet)
                {
                    try
                    {
                        isChanged = false;
                        //set text in variable to Vienna value
                        double val = Convert.ToDouble(this.Text);
                        if (val < _minValue)
                        {
                            //set minimum value
                            this.Text = _minValue.ToString();

                        }
                        else
                            if (val > _maxValue)
                            {
                                //set maximum value
                                this.Text = _maxValue.ToString();
                            }
                        isChanged = true;
                    }
                    catch
                    {
                    }
                }
                //Commented for SL, rewrite immediate in below line
                //if (EditingControlDataGridView == null && e.KeyCode == Keys.Enter)
                if (e.Key == Key.Enter)
                {
                    if (VetoableChangeListener != null)
                        VetoableChangeListener(this, e);
                }
                else
                {
                    if (FireTextChanged != null)
                    {
                        FireTextChanged(this, EventArgs.Empty);

                    }

                }
            }
            //  e.Handled = true;
        }

        protected void Dispose(bool disposing)
        {

            //base.Dispose(disposing);
            _field = null;



            VetoableChangeListener = null;
        }


        #region "IDataGridViewEditingCOntrol Inteface"
        //Commente for SL whole region
        ///// <summary>
        ///// Grid cell style
        ///// Implements the IDataGridViewEditingControl.ApplyCellStyleToEditingControl method
        ///// </summary>
        ///// <param name="dataGridViewCellStyle">cell style</param>
        //public void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle)
        //{
        //}

        ///// <summary>
        ///// Row index
        ///// Implements the IDataGridViewEditingControl.EditingControlRowIndex property
        ///// </summary>
        //public int EditingControlRowIndex
        //{
        //    get;
        //    set;
        //}


        ///// <summary>
        ///// Key press event in the grid view
        ///// Implements the IDataGridViewEditingControl.EditingControlWantsInputKey 
        ///// </summary>
        ///// <param name="key">pressed key</param>
        ///// <param name="dataGridViewWantsInputKey">bool value</param>
        ///// <returns>bool type</returns>
        //public bool EditingControlWantsInputKey(Keys key, bool dataGridViewWantsInputKey)
        //{
        //    // Let the Control handle the keys listed.
        //    switch (key & Keys.KeyCode)
        //    {
        //        case Keys.Left:
        //        case Keys.Up:
        //        case Keys.Down:
        //        case Keys.Right:
        //        case Keys.Home:
        //        case Keys.End:
        //        case Keys.PageDown:
        //        case Keys.PageUp:
        //            return true;
        //        default:
        //            return false;
        //    }
        //}

        ///// <summary>
        ///// Prepare editing
        ///// Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit method
        ///// </summary>
        ///// <param name="selectAll">bool value</param>
        //public void PrepareEditingControlForEdit(bool selectAll)
        //{
        //    this.SelectAll();
        //    isSelected = true;
        //    // No preparation needs to be done.
        //}

        ///// <summary>
        ///// Repositioning the control
        ///// Implements the IDataGridViewEditingControl.RepositionEditingControlOnValueChange property
        ///// </summary>
        //public bool RepositionEditingControlOnValueChange
        //{
        //    get
        //    {
        //        return false;
        //    }
        //}

        ///// <summary>
        ///// Editing grid control
        ///// Implements the IDataGridViewEditingControl.EditingControlDataGridView property
        ///// </summary>
        //public DataGridView EditingControlDataGridView
        //{
        //    get;
        //    set;
        //}
        //public bool EditingControlValueChanged
        //{
        //    get;
        //    set;
        //}

        ///// <summary>
        ///// Set Cursor
        ///// Implements the IDataGridViewEditingControl.EditingPanelCursor property
        ///// </summary>
        //public Cursor EditingPanelCursor
        //{
        //    get
        //    {
        //        return this.Cursor;
        //    }
        //}
        //public object EditingControlFormattedValue
        //{
        //    get { return this.Text; }
        //    set { this.Text = value.ToString(); }
        //}

        ///// <summary>
        ///// Get formatted value of control in grid
        ///// Implements IDataGridViewEditingControl.GetEditingControlFormattedValue method.
        ///// </summary>
        ///// <param name="context">context</param>
        ///// <returns>object</returns>
        //public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context)
        //{
        //    return EditingControlFormattedValue;
        //}
        #endregion

        public void SetAtttribute(Grids.GridField field)
        {
            //this.TextChanged -= new EventHandler(TextBox_TextChanged);
            // this.KeyUp -= new KeyEventHandler(VAmountTextBox_KeyUp);

            _columnName = field.GetColumnName();
            _displayType = field.GetDisplayType();
            _format = DisplayType.GetNumberFormat(_displayType);
            SetField(field);
            //this.TextChanged += new EventHandler(TextBox_TextChanged);
            // this.KeyUp +=new KeyEventHandler(VAmountTextBox_KeyUp);

        }



        protected void OnTextChanged(EventArgs e)
        {
            SetColor();
        }
        /// <summary>
        /// On click select all the text in the amount text control
        /// </summary>
        /// <param name="e"></param>
        protected override void OnGotFocus(RoutedEventArgs e)
        {
            _focus = true;
            base.OnGotFocus(e);
            if (!isSelected)
            {
                this.SelectAll();
                isSelected = true;
            }
        }
        //protected void OnClick(EventArgs e)
        //{
        //    if (!isSelected)
        //    {
        //        this.SelectAll();
        //        isSelected = true;
        //    }
        //}

        //protected override void OnKeyDown(KeyEventArgs e)
        //{
        //    base.OnKeyDown(e);
        //}
        /// <summary>
        /// process key board key's message
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        //Commented for SL
        //protected override bool ProcessKeyMessage(ref Message m)
        //{
        //    bool b = base.ProcessKeyMessage(ref m);
        //    /* to resolve special char like (#,!,& etc) accept problrm in datagridview editing control*/
        //    if (b && EditingControlDataGridView != null)
        //    {
        //        return ProcessKeyEventArgs(ref m);
        //    }
        //    return b;
        //}

        //internal void SetRange(string p, string p_2)
        //{
        //    throw new NotImplementedException();
        //}

        //internal void SetField(Grids.GridField mField)
        //{
        //    throw new NotImplementedException();
        //}


        public bool Focused
        {
            get { return _focus; }
        }

        public void Dispose()
        {
            binding = null;
        }


        public string BindValue
        {
            set
            {
                binding = new Binding(value);
                binding.Mode = BindingMode.OneWay;
                this.SetBinding(VAmountTextBox.TextValueProperty, binding);
            }
        }


        public void SetName(string name)
        {
            this._columnName = name;
        }

        public bool IsDisabled()
        {
            return !this.IsEnabled;
        }

        public void SetDisabled(bool disabled)
        {
            this.IsEnabled = !disabled;
        }

        public int GetTabIndex()
        {
            return this.TabIndex;
        }

        public void SetTabindex(int tabindex)
        {
            this.TabIndex = tabindex;
        }

        public bool Multiline
        {
            get
            {
                return false;
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public bool Visible
        {
            get
            {
                return this.Visibility == System.Windows.Visibility.Visible;
            }
            set
            {
                this.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            }
        }
    }
}
